﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GrapecityReportsLibrary.Controls;
using System.Data.OleDb;
using Grapecity.PowerTools.Api.Models;
using System.Net;
using System.IO;
using System.Diagnostics;
using GrapeCity.ActiveReports;

namespace GrapecityReportsLibrary
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();

            G_Global.App_Init();
        }


        public User user = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            //CommonFunctions.AddARDemoOperation(EventTypes.打开模板库, null);

            // 检查是否已经安装 Sqlite 驱动
            if (!CommonFunctions.CheckInstalledSqliteDriver())
            {
                InstallerProcess frmProcess = new InstallerProcess();
                DialogResult result = frmProcess.ShowDialog();

                if (result != DialogResult.OK)
                {
                    MessageBox.Show("缺少 Sqlite 数据库驱动模板库将无法运行，如需使用模板库请，请再次安装便可！", "环境安装", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Application.Exit();
                }
            }

            // 创建报表菜单
            BuildReportMenu();

            // 加载广告对应图片和点击之后的跳转URL
            LoadAdvertise();

            // 挂接改变类别时的事件
            reportsMenu1.CategoryClick += ReportsMenu1_CategoryClick;
            reportsMenu1.SeriesClick += ReportsMenu1_SeriesClick;
            
            // 发送跟踪统计请求
            G_Global.CallWebApi("START UP", "", "", "");
        }

        private void ReportsMenu1_CategoryClick(object sender, EventArgs e)
        {
            MenuItemControl item = (sender as MenuItemControl);

            if (item == null || item.Reports == null || item.Reports.Count == 0)
                return;

            foreach (var ctl in this.flowPnlMain.Controls)
            {
                if (ctl is HomeItemControl)
                {
                    ((HomeItemControl)ctl).ReportClick -= I_ReportClick;
                }
            }

            this.flowPnlMain.Controls.Clear();

            foreach (var report in item.Reports.OrderBy(r => r.FunctionCateoryOrder))
            {
                HomeItemControl i = new HomeItemControl();
                i.ReportID = report.ID;

                string imgPath = Application.StartupPath + "\\Images\\报表缩略图\\" + report.ID + ".jpg";
                if (!File.Exists(imgPath))
                {
                    imgPath = Application.StartupPath + string.Format("\\Images\\报表缩略图\\{0}", report.Name + ".jpg");
                    if (!File.Exists(imgPath))
                    {
                        imgPath = Application.StartupPath + string.Format("\\Images\\报表缩略图\\{0}\\{1}", report.FunctionCateory, report.Name + ".jpg");

                        if (!File.Exists(imgPath))
                        {
                            imgPath = Application.StartupPath + string.Format("\\Images\\报表缩略图\\{0}\\{1}", report.FunctionCateory, report.Path.Replace(".rdlx","") + ".jpg");
                        }
                    }
                }

                //ExportJpeg(report);

                try
                {
                    i.Icon = Image.FromFile(imgPath);
                    i.FunctionName = report.Name;
                    i.Width = 273;
                    i.Height = 182;
                    i.IsNewReport = report.IsNew;

                    this.flowPnlMain.Controls.Add(i);
                    i.ReportClick += I_ReportClick;
                }
                catch
                {
                    // export the jpeg for each report
                    //ExportJpeg(report);
                }
            }

            this.flowPnlMain.BringToFront();
        }

        private void ExportJpeg(Report report)
        {
            try
            {
                string filename = string.Format(@"{0}\{1}\{2}\{3}\{4}", Application.StartupPath, "Reports", report.SystemCategory, report.FunctionCateory, report.Path);
                //string filename1 = string.Format(@"D:\onedrive\OneDrive - GrapeCity Group\报表\模板库\对外推广资料\视频脚本\资源\report-images\{0}", report.Path);
                PageReport pReport = new PageReport(new FileInfo(filename));

                GrapeCity.ActiveReports.Export.Image.Page.ImageRenderingExtension imageRenderingExtension = new GrapeCity.ActiveReports.Export.Image.Page.ImageRenderingExtension();
                GrapeCity.ActiveReports.Rendering.IO.MemoryStreamProvider outputProvider = new GrapeCity.ActiveReports.Rendering.IO.MemoryStreamProvider();
                GrapeCity.ActiveReports.Export.Image.Page.Settings setting = new GrapeCity.ActiveReports.Export.Image.Page.Settings();
                //setting.ImageType = GrapeCity.ActiveReports.Export.Image.Page.Renderers.ImageType.JPEG;
                setting.ImageType = GrapeCity.ActiveReports.Export.Image.Page.Renderers.ImageType.PNG;
                setting.Quality = 100;

                pReport.Document.Render(imageRenderingExtension, outputProvider, setting);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    // Get the first page of the report
                    outputProvider.GetSecondaryStreams()[0].OpenStream().CopyTo(ms);

                    Bitmap bmSave = new Bitmap(System.Drawing.Image.FromStream(ms));
                    bmSave.Save(filename.Replace(".rdlx", ".png"));
                }
            } catch { }
        }

        private void ReportsMenu1_SeriesClick(object sender, EventArgs e)
        {
            //string buttonType = (sender as LinkButtonControl).ButtonText;

            //var reports = GetReports();


            //if (buttonType == "报表功能")
            //{
            //    this.functionControl1.BringToFront();
            //}
            //else
            //{   
            //    this.industryControl1.BringToFront();
            //}
        }

        private void I_ReportClick(object sender, EventArgs e)
        {
            homePageControl1_ReportClick(sender, e);
        }

        private void reportsMenu1_ReportClick(object sender, EventArgs e)
        {
            this.reportViewerControl1.BringToFront();
            Report report = (sender as MenuChildControl).Report;
            this.reportViewerControl1.LoadReport(report);
        }

        private void BuildReportMenu()
        {
            // 获取全部报表
            List<Report> reports = GetReports();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            sw.Start();

            // 报表菜单
            List<GrapecityReportsLibrary.Controls.MenuItem> menutree = new List<GrapecityReportsLibrary.Controls.MenuItem>();

            
            // 创建报表菜单
            foreach (var items in reports.Where(r => r.SystemCategory == "行业案例").OrderBy(r => r.SystemCategoryOrder).ThenBy(r => r.ID).GroupBy(r => r.FunctionCateory))
            {
                GrapecityReportsLibrary.Controls.MenuItem menu = new GrapecityReportsLibrary.Controls.MenuItem();

                Category category = new Category();

                menu.Category = category;
                menu.Reports = items.Where(r => r.IsHide == false).ToList<Report>();
                category.Name = menu.Reports[0].FunctionCateory;
                category.SystemCategory = menu.Reports[0].SystemCategory;
                category.Icon = category.Name;

                menutree.Add(menu);
            }

            //reportsMenu1.BuildMenu("行业案例", menutree);

            // 报表菜单
            List<GrapecityReportsLibrary.Controls.MenuItem> menutree2 = new List<GrapecityReportsLibrary.Controls.MenuItem>();

            // 创建报表菜单
            foreach (var items in reports.Where(r => r.SystemCategory == "报表功能").OrderBy(r => r.SystemCategoryOrder).ThenBy(r => r.ID).GroupBy(r => r.FunctionCateory))
            {
                GrapecityReportsLibrary.Controls.MenuItem menu = new GrapecityReportsLibrary.Controls.MenuItem();

                Category category = new Category();

                menu.Category = category;
                menu.Reports = items.Where(r => r.IsHide == false).ToList<Report>();
                category.Name = menu.Reports[0].FunctionCateory;
                category.SystemCategory = menu.Reports[0].SystemCategory;
                category.Icon = category.Name;

                menutree2.Add(menu);
            }

            

            reportsMenu1.BuildMenu("报表功能", menutree2);
            reportsMenu1.BuildMenu("行业案例", menutree);
            sw.Stop();
            string result1 = sw.Elapsed.TotalSeconds.ToString();

        }

        private List<Report> GetReports()
        {
            List<Report> reports = new List<Report>();

            string conStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\GrapecityReportsLibrary.mdb;Persist Security Info=False";

            DataTable dt = new DataTable();
            DataTable dt2 = new DataTable();

            using (OleDbDataAdapter oda = new OleDbDataAdapter("select * from 行业案例;", conStr))
            {
                if (new OleDbConnection().State == ConnectionState.Closed)
                {
                    new OleDbConnection(conStr).Open();
                }

                oda.Fill(dt);

                oda.SelectCommand.CommandText = "select * from 报表功能";

                oda.Fill(dt2);

                dt.Merge(dt2);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Report report = new Report();
                report.ID = dt.Rows[i]["报表编号"].ToString();
                report.SystemCategory = dt.Rows[i]["系统分类"].ToString();
                report.SystemCategoryOrder = int.Parse(dt.Rows[i]["功能分类序号"].ToString());
                report.FunctionCateory = dt.Rows[i]["功能分类"].ToString();
                report.FunctionCateoryOrder = int.Parse(dt.Rows[i]["报表序号"].ToString());
                report.Name = dt.Rows[i]["报表名称"].ToString();
                report.Path = dt.Rows[i]["存放路径"].ToString();
                report.Description = dt.Rows[i]["报表说明"].ToString();
                report.ReferURL = dt.Rows[i]["参考教程"].ToString();
                report.Version = dt.Rows[i]["版本号"].ToString();
                report.CreateDate = DateTime.Parse(dt.Rows[i]["创建时间"].ToString());

                if (!string.IsNullOrEmpty(dt.Rows[i]["更新时间"].ToString()))
                {
                    report.LastModifiedDate = DateTime.Parse(dt.Rows[i]["更新时间"].ToString());
                }

                report.ModifiedComment = dt.Rows[i]["更新说明"].ToString();
                report.IsSystem = bool.Parse(dt.Rows[i]["系统推荐"].ToString());
                report.IsHide = bool.Parse(dt.Rows[i]["隐藏报表"].ToString());

                report.WebUrl = dt.Rows[i]["WebUrl"].ToString();
                report.IsNew = bool.Parse(dt.Rows[i]["IsNew"].ToString());

                reports.Add(report);
            }

            return reports.OrderBy(r => r.FunctionCateoryOrder).ToList<Report>();
        }

        private void homePageControl1_ReportClick(object sender, EventArgs e)
        {
            HomeItemControl reportitem = (sender as HomeItemControl);
            if (reportitem.ReportID.StartsWith("M"))
            {
                ProcessStartInfo sInfo = new ProcessStartInfo("https://demo.grapecity.com.cn/activereports/aspnet/mobile/indexWeb.html?utm_source=Demo&utm_medium=ActiveReports&utm_term=GrapecityReportsLibrary&utm_content=armobiledemo");
                Process.Start(sInfo);
                //this.reportBrowserViewerControl1.BringToFront();
                //this.reportBrowserViewerControl1.LoadReport("https://demo.grapecity.com.cn/activereports/aspnet/mobile/indexWeb.html?utm_source=Demo&utm_medium=ActiveReports&utm_term=GrapecityReportsLibrary&utm_content=armobiledemo");
            }
            else
            {
                reportsMenu1.SelectReport(GetReports().First(r => r.ID == reportitem.ReportID));

                this.reportViewerControl1.BringToFront();
                this.reportViewerControl1.LoadReport(GetReports().First(r => r.ID == reportitem.ReportID));
            }
        }

        private void productLogoControl1_ProductLogoClick(object sender, EventArgs e)
        {
            this.homePageControl1.BringToFront();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            G_Global.CallWebApi("CLOSE", "", "", "");
            //CommonFunctions.AddARDemoOperation(EventTypes.关闭模板库, null);
        }

        private void linkButtonControl1_ButtonClick(object sender, EventArgs e)
        {
            LinkButtonControl btnUrl = sender as LinkButtonControl;
            //CommonFunctions.AddARDemoOperation(EventTypes.点击菜单, btnUrl.ButtonText);
            System.Diagnostics.Process.Start(btnUrl.LinkUrl);
        }

        private void linkButtonControl4_ButtonClick(object sender, EventArgs e)
        {
            //CommonFunctions.AddARDemoOperation(EventTypes.点击菜单, "关于我们");

            ContactUs frm = new ContactUs();
            frm.ShowDialog();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            //CommonFunctions.AddARDemoOperation(EventTypes.点击广告, "点击模板库广告");
            System.Diagnostics.Process.Start(pictureBox2.Tag.ToString());
        }

        private void LoadAdvertise()
        {
            using (WebClient wc = new WebClient())
            {
                try
                {
                    // 获取当前广告对应的配置信息，图片名称和调整URL
                    System.IO.Stream stream = null;
                    stream = wc.OpenRead(new Uri("http://www.grapecity.com.cn/enterprise-solutions/demo/ars/library/client/link/config.txt"));
                    System.IO.StreamReader sr = new System.IO.StreamReader(stream, Encoding.Unicode);
                    string picturename = sr.ReadLine();
                    string pictureurl = sr.ReadLine();

                    // 设置广告图片
                    stream = wc.OpenRead(new Uri(string.Format("http://www.grapecity.com.cn/enterprise-solutions/demo/ars/library/client/link/{0}", picturename)));
                    Image image = Image.FromStream(stream);
                    this.pictureBox2.Image = image;

                    // 设置广告调整URL
                    this.pictureBox2.Tag = pictureurl;

                    //// 将服务器图片保存在本地，以便在断网的情况下也能加载最新的广告内容
                    //if (!File.Exists(@"Customer"))
                    //{
                    //    Directory.CreateDirectory("Customer");
                    //}
                    //if (File.Exists(string.Format(@"Customer\{0}", picturename)))
                    //{
                    //    File.Delete(string.Format(@"Customer\{0}", picturename));
                    //}
                    //image.Save(string.Format(@"Customer\{0}", picturename));

                }
                catch (Exception)
                {
                    wc.Dispose();
                }
            }
        }

        private void linkButtonControl2_ButtonClick(object sender, EventArgs e)
        {
            LinkButtonControl btnUrl = sender as LinkButtonControl;
            //CommonFunctions.AddARDemoOperation(EventTypes.点击菜单, btnUrl.ButtonText);
            System.Diagnostics.Process.Start(btnUrl.LinkUrl);
        }
    }
}
